// pages/resourcesShow/resourcesShow.js
import {
  request
} from "../../request/index.js";
const util = require("../../utils/util.js")
var app = getApp();
var icon = true;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    playIcon: "/images/资源展示图标_slices/路径@2x.png", //默认图片地址
    title: "点击收藏",
    resource: {},
    resourcePic: [],
    user: {},
    _user: {},
    ic: "",
    maskHidden: false,
    tempFilePath: "",
    hid: false,
    path: "",
    path3: ""
  },
  checkMember() {
    var time = this.data.user.memberDueDate
    var dd = util.formatDate(new Date())
    var that = this
    var userId = app.globalData.userId;
    if(this.data.user.userType==1){
      wx.showToast({
        title: '您不是会员，请充值查看',
        icon: "none",
        duration: 1500
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/member/member?userId=' + userId + "&userIdByResource=" + that.data.resource.userId,
        })
      }, 1500)
      return;
    }
    if (!time) {
      wx.showToast({
        title: '您不是会员，请充值查看',
        icon: "none",
        duration: 1000
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/member/member?userId=' + userId+"&userIdByResource="+that.data.resource.userId,
        })
      }, 1500)
    } else {
      if (dd > time) {
        wx.showToast({
          title: '您的会员已到期，请充值查看',
          icon: "none",
          duration: 1000
        })
        setTimeout(function () {
          wx.navigateTo({
            url: '/pages/member/member?userId=' + userId+"&userIdByResource="+that.data.resource.userId,
          })
        }, 1500)
      } else {
        request({
          url: "/UserInfo/getUserViewPhoneLogByUserId",
          data: {
            userId: userId
          }
        }).then(res => {
          var flag=false;
          for(var i=0;i<res.data.length;i++){
            if(res.data[i].resourcesId==that.data.resource.resourcesId){
              flag=true;
            }
          }
          if(that.data.user.userType==0){
            flag=true
          }
          if(flag==true){
            wx.showModal({
              title: "电话",
              content: that.data.resource.phone,
              success(res) {
                if (res.confirm) {
                  wx.makePhoneCall({
                    phoneNumber: that.data.resource.phone,
                  })
                } else if (res.cancel) {}
              }
            })
          }else if (res.data.length < 7&&flag==false) {
            request({
                  url:"/UserInfo/addUserViewPhoneLog",
                  data:{
                    userId:userId,
                    resourcesId:that.data.resource.resourcesId,
                    phone:that.data.resource.phone
                  }
                })
            wx.showModal({
              title: "电话",
              content: that.data.resource.phone,
              success(res) {
                if (res.confirm) {
                  wx.makePhoneCall({
                    phoneNumber: that.data.resource.phone,
                  })
                } else if (res.cancel) {}
              }
            })

          } else {
            wx.showToast({
              title: '您今日的查看次数已达上限',
              icon: "none",
              duration: 1500
            })
          }

        })
      }
    }
  },
  tapVoicePlay: function (e) {
    var userId = app.globalData.userId;
    var resourcesId = this.data.resource.resourcesId;
    if (e.currentTarget.dataset.val == 0) {
      this.setData({
        ic: 1
      })
      request({
        url: "/Favorite/addFavorite",
        data: {
          userId: userId,
          resourcesId: resourcesId
        }
      }).then(res => {

      })
    } else if (e.currentTarget.dataset.val == 1) {
      this.setData({
        ic: 0
      })
      request({
        url: "/Favorite/delFavorite",
        data: {
          userId: userId,
          resourcesId: resourcesId
        }
      }).then(res => {

      })
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.isshare == 1) {
      wx.navigateTo({
        url: '../guang/guang?resourcesId='+options.resourcesId
      })
    }
    const {
      resourcesId
    } = options;
    var userId = app.globalData.userId;
    var that = this
    request({
      url:"/Resources/addResourcesVisitsNumber",
      data:{
        resourcesId:resourcesId
      }
    }).then(res=>{
      
    })
    request({
      url:"/Favorite/isFavorite",
      data:{
        userId:userId,
        resourcesId:resourcesId
      }
    }).then(re=>{
      if(re.data==0){
        this.setData({
          ic:0
        })
      }else{
        this.setData({
          ic:1
        })
      }
    })
    request({
      url: "/Resources/getResource",
      data: {
        resourcesId: resourcesId
      }
    }).then(res => {
      if (res.data.resourcesType == 2) {
        this.setData({
          hid: true
        })
      }
      this.setData({
        resource: res.data
      })
    });
    request({
      url: "/Resources/getResourcesPic",
      data: {
        resourcesId: resourcesId
      }
    }).then(r => {
      this.setData({
        resourcePic: r.data
      })
      var path = r.data[0].pictureUrl 
      
      wx.getImageInfo({
        src: path,
        success: function (res) {
          that.setData({
            path: res.path
          })
        }
      })
    });
    request({
      url: "/UserInfo/getUserInfo",
      data: {
        userId: userId
      }
    }).then(re => {
      this.setData({
        user: re.data
      })
    });
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowW: res.windowWidth,
          windowH: res.windowHeight,
          rpx:res.windowWidth/375
        })
      },
    })
    var userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo: userInfo
    })
    console.log('userInfo============'+userInfo)
    if (!userInfo) {
      wx.getUserProfile({
        desc: "s",
        success: (res) => {
          wx.setStorageSync('userInfo', res.userInfo)
          this.setData({
            userInfo: res.userInfo
          })
          var path3 = res.userInfo.avatarUrl
          wx.getImageInfo({
            src: path3,
            success: function (r) {
              that.setData({
                path3: r.path
              })
            }
          })
        }
      })
    } else {
      var path3 = userInfo.avatarUrl
      wx.getImageInfo({
        src: path3,
        success: function (r) {
          that.setData({
            path3: r.path
          })
        }
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      _user: wx.getStorageSync('user')
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      path: '/pages/resourcesShow/resourcesShow?isshare=1&resourcesId='+this.data.resource.resourcesId,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },



  newLine(txt, context) {
    var txtArr = txt.split('')
    var temp = ''
    var row = []
    for (var i = 0; i < txtArr.length; i++) {
      if (context.measureText(temp).width < this.data.rpx *100) {
        temp += txtArr[i]
      } else {
        i--
        row.push(temp)
        temp = ''
      }
    }
    row.push(temp)
    //如果数组长度大于3 则截取前三个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 172 * this.data.rpx) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示三行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    return row
  },




  createNewImg: function () {
    var that = this;
    console.log(that.data)
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fff")
    context.fillRect(0, 0, this.data.windowW, this.data.windowH)
    var path1 = "/icon/shui.png"
    var path2 = "/images/ma(1).jpg"
    context.drawImage(that.data.path, 0, 0, 280 * that.data.rpx,280*that.data.rpx);
    context.drawImage(path1, 0, 0,  280 * that.data.rpx,280*that.data.rpx);
    context.save();
    context.beginPath();
    context.arc(24*that.data.rpx, 372* that.data.rpx, 12 * that.data.rpx, 0, Math.PI * 2, false);
    context.clip();
    context.drawImage(that.data.path3, 12*that.data.rpx, 360* that.data.rpx, 24 * that.data.rpx, 24 * that.data.rpx);
    context.restore();
    context.drawImage(path2, that.data.rpx * 182, 300 * that.data.rpx, that.data.rpx * 96, that.data.rpx * 96);
    var row = that.newLine(this.data.resource.resourcesDescribe, context)
    var a = 23 
    for (var i = 0; i < row.length; i++) {
      context.setFontSize(16)
      context.setFillStyle("#000000")
      context.fillText(row[i],10, (this.data.rpx) * 300 + a * i)
    }
    context.setFontSize(16);
    context.setFillStyle('#333');
    context.setTextAlign('left');
    context.setFillStyle("red")
    context.fillText(this.data.userInfo.nickName, 40 * this.data.rpx, 378* this.data.rpx);
    context.stroke();
    setTimeout(function () {
      context.draw();
    }, 500)
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 600);
  },
  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '海报已保存到相册',
          showCancel: false,
          confirmText: '确定',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              /* 该隐藏的隐藏 */
              that.setData({
                maskHidden: false
              })
            }
          },
          fail: function (res) {}
        })
      }
    })
  },
  //点击生成
  formSubmit: function (e) {
    var that = this;
    this.setData({
      maskHidden: false
    });
    var userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo: userInfo
    })
    if (!userInfo) {
      wx.getUserProfile({
        desc: "ss",
        success: (res) => {
          wx.setStorageSync('userInfo', res.userInfo)
          this.setData({
            userInfo: res.userInfo
          })
          var path3 = res.userInfo.avatarUrl
          wx.getImageInfo({
            src: path3,
            success: function (r) {
              that.setData({
                path3: r.path
              })
            }
          })
          wx.showToast({
            title: '海报生成中...',
            icon: 'loading',
            duration: 1500
          });
          setTimeout(function () {
            wx.hideToast()
            that.createNewImg();
            that.setData({
              maskHidden: true
            });
          }, 1000)
        },
        fail: function () {
          wx.showToast({
            title: '需要您的信息才可以生成海报',
            icon: "none",
            duration: 1000
          })
        }
      })
    } else {
      wx.showToast({
        title: '海报生成中...',
        icon: 'loading',
        duration: 1500
      });
      setTimeout(function () {
        wx.hideToast()
        that.createNewImg();
        that.setData({
          maskHidden: true
        });
      }, 1000)
    }

  },

  async getPhoneNumber(e) {
    try {
      const { code } = e.detail
      const { id } = e.target.dataset

      if (!code) {
        return
      }

      const res = await app.goLoginPub(code)
      this.checkMember()

    } catch (error) {
      console.log('error :>> ', error);
    }
  },
  
  goLogin() {
    wx.navigateTo({
      url: '/pages/loginPage/loginPage'
    })
  }
})